//插件加载
import plugin from '../../../lib/plugins/plugin.js'
import data from '../model/XiuxianData.js'
import config from "../model/Config.js"
import {Read_player,existplayer,ForwardMsg,isNotNull} from './xiuxian.js'
import {Add_灵石,Add_修为} from './xiuxian.js'

/**
 * 秘境模块
 */

let allaction=false;

export class SecretPlace extends plugin {
    constructor() {
        super({
            name: 'Yunzai_Bot_SecretPlace',
            dsc: '修仙模块',
            event: 'message',
            /** 
             * 优先级，数字越小等级越高，建议优先级600
             */
            priority: 600,
            rule: [
                {
                    reg: '^#修仙状态$',
                    fnc: 'Xiuxianstate'
                },
                {
                    reg: '^#秘境$',
                    fnc: 'Secretplace'
                },
                {
                    reg: '^#降临秘境.*$',
                    fnc: 'Gosecretplace'
                },
                {
                    reg: '^#仙府$',
                    fnc: 'Timeplace'
                },
                {
                    reg: '^#探索仙府$',
                    fnc: 'GoTimeplace'
                },
                {
                    reg: '^#禁地$',
                    fnc: 'Forbiddenarea'
                },
                {
                    reg: '^#前往禁地.*$',
                    fnc: 'Goforbiddenarea'
                },
                {
                    reg: '^#放弃探索',
                    fnc: 'Giveup'
                }
            ]
        })
        this.xiuxianConfigData = config.getConfig("xiuxian", "xiuxian");
    }

    
    async Xiuxianstate(e){
        Go(e);
        allaction=false;
        return;
    }


    async Giveup(e){
        e.reply("功能待实现");
        return;
    }



    //秘境地点
    async Secretplace(e) {
        let addres="秘境";
        let weizhi = data.didian_list;
        Goweizhi(e,weizhi,addres);
    }

    //限定仙府
    async Timeplace(e) {
        let addres="仙府";
        let weizhi = data.timeplace_list
        Goweizhi(e,weizhi,addres);
    }
    
     //禁地
     async Forbiddenarea(e) {
        let addres="禁地";
        let weizhi = data.forbiddenarea_list
        Goweizhi(e,weizhi,addres);
    }




    //前往秘境
    async Gosecretplace(e) {

        let usr_qq = e.user_id;

        //行为检查
        await Go(e);
        if(allaction){
            console.log(allaction);
        }
        else{
            return;
        }
        allaction=false;

         //不开放私聊
         if (!e.isGroup) {
            e.reply("此功能暂时不开放私聊");
            return;
        }


        let player = await Read_player(usr_qq);
        var didian = e.msg.replace("#降临秘境", '');
        didian = didian.trim();
        let weizhi = await data.didian_list.find(item => item.name == didian);
        if (!isNotNull(weizhi)) {
            //直接返回
            return;
        }

        
        if (player.灵石 < weizhi.Price) {
            e.reply("没有灵石寸步难行,攒到" + weizhi.Price+ "灵石才够哦~");
            return true;
        }
        
        //检查境界
        let now_level = player.境界
        let now_level_id = data.Level_list.find(item => item.level == now_level).level_id;


        if (didian == "方诸山" || didian == "昆仑山" || didian == "蓬莱岛") {
            if (now_level_id < 34) {
                e.reply("天道：凡人！你不该出现在这里！\n你尝试前往仙界，被天道发现了！");
                return;
            }
            else{
                //检查仙门
                let power_place = await redis.get("xiuxian:player:" + usr_qq + ":power_place");
                if (power_place != 0) {
                e.reply("你已无法重返仙界！");
                return;
                }
            }
        }

        
        var time=this.xiuxianConfigData.CD.secretplace;//时间（分钟）
        let action_time = 60000 * time;//持续时间，单位毫秒
        let arr = {
            "action": "历练",//动作
            "end_time": new Date().getTime() + action_time,//结束时间
            "time": action_time,//持续时间
            "shutup":"1",//闭关
            "working":"1",//劳动
            "Place_action": "0",//秘境状态---开启
            "Place_actionplus": "1",//沉迷秘境状态---关闭
            "power_up": "1",//渡劫状态--关闭
            //这里要保存秘境特别需要留存的信息
            "Place_address":weizhi,
        };
        //消息推送
        if (e.isGroup) {
            arr.group_id = e.group_id
        }
        //redis设置动作
        await redis.set("xiuxian:player:" + usr_qq + ":action", JSON.stringify(arr));
        Add_灵石(usr_qq, -weizhi.Price);
        e.reply("开始降临" + didian + "," + time + "分钟后归来!");
        return;
    }


    //探索仙府
    async GoTimeplace(e){
        let usr_qq = e.user_id;

        //行为检查
        await Go(e);
        if(allaction){
            console.log(allaction);
        }
        else{
            return;
        }
        allaction=false;

         //不开放私聊
         if (!e.isGroup) {
            e.reply("此功能暂时不开放私聊");
            return;
        }



        //用户信息
        let player = await Read_player(usr_qq);
        let didian = "无欲天仙";


        //查询秘境
        let weizhi = await data.timeplace_list.find(item => item.name == didian);
        if (!isNotNull(weizhi)) {
            //直接返回
            return;
        }


        //灵石不够了
        if (player.灵石 < weizhi.Price) {
            e.reply("没有灵石寸步难行,攒到" + weizhi.Price+ "灵石才够哦~");
            return ;
        }


        var time=this.xiuxianConfigData.CD.timeplace;//时间（分钟）
        let action_time = 60000 * time;//持续时间，单位毫秒
        let arr = {
            "action": "探索",//动作
            "end_time": new Date().getTime() + action_time,//结束时间
            "time": action_time,//持续时间
            "shutup":"1",//闭关
            "working":"1",//劳动
            "Place_action": "0",//秘境状态---开启
            "Place_actionplus": "1",//沉迷秘境状态---关闭
            "power_up": "1",//渡劫状态--关闭
            //这里要保存秘境特别需要留存的信息
            "Place_address":weizhi,
        };


        //消息推送
        if (e.isGroup) {
            arr.group_id = e.group_id
        }


        //redis设置动作
        await redis.set("xiuxian:player:" + usr_qq + ":action", JSON.stringify(arr));
        Add_灵石(usr_qq, -weizhi.Price);
        e.reply("开始探索"+weizhi.name+"的仙府," + time + "分钟后归来!");
        return;

    }

    //前往禁地
    async Goforbiddenarea(e){
        let usr_qq = e.user_id;

         //行为检查
        await Go(e);
        if(allaction){
            console.log("通过");
        }
        else{
            return;
        }
        allaction=false;

         //不开放私聊
         if (!e.isGroup) {
            e.reply("此功能暂时不开放私聊");
            return;
        }



        //查仙门
        let power_place = await redis.get("xiuxian:player:" + usr_qq + ":power_place");
        //有仙门
        if (power_place == 0) {
                e.reply("仙人不可下界！");
                return;
         }


         //查境界
        let player = await Read_player(usr_qq);
        let now_level = player.境界;
        let now_level_id = await data.Level_list.find(item => item.level == now_level).level_id;
        if(now_level_id>=21&&now_level_id<34){
            //境界控制在---炼虚初期-----渡劫期（高级玩法）
            console.log("允许");
        }
        else{
            e.reply("你的实力不符合禁地要求！");
            return;
        }


        //判断地点
        var didian = await e.msg.replace("#前往禁地", '');
        didian = didian.trim();

        //检查地点
        let  weizhi = await data.forbiddenarea_list.find(item => item.name == didian);
        if (!isNotNull(weizhi)) {
            return;
        }


  
        if (player.灵石 < weizhi.Price) {
            e.reply("没有灵石寸步难行,攒到" + weizhi.Price+ "灵石才够哦~");
            return true;
        }
        if (player.修为 < weizhi.experience) {
            e.reply("你需要积累"+weizhi.experience+"修为，才能抵抗禁地魔气！");
            return true;
        }


        var time=this.xiuxianConfigData.CD.forbiddenarea;//时间（分钟）
        let action_time = 60000 * time;//持续时间，单位毫秒
        let arr = {
            "action": "禁地",//动作
            "end_time": new Date().getTime() + action_time,//结束时间
            "time": action_time,//持续时间
            "shutup":"1",//闭关
            "working":"1",//劳动
            "Place_action": "0",//秘境状态---开启
            "Place_actionplus": "1",//沉迷秘境状态---关闭
            "power_up": "1",//渡劫状态--关闭
            //这里要保存秘境特别需要留存的信息
            "Place_address":weizhi,
        };

        //消息推送
        if (e.isGroup) {
            arr.group_id = e.group_id
        }

        //redis设置动作
        await redis.set("xiuxian:player:" + usr_qq + ":action", JSON.stringify(arr));
        await Add_灵石(usr_qq, -weizhi.Price);
        await Add_修为(usr_qq, -weizhi.experience);

        e.reply("正在前往"+weizhi.name+","+ time + "分钟后归来!");
        return;
    }

}

/**
     * 地点查询
 */
 export async function Goweizhi(e,weizhi,addres){
    let adr=addres;
    let msg = [
        "***"+adr+"***"
    ];
    for (var i = 0; i < weizhi.length; i++) {
        msg.push(weizhi[i].name + "\n" + "等级：" + weizhi[i].Grade + "\n" + "极品：" + weizhi[i].Best[0] + "\n" + "灵石：" + weizhi[i].Price + "灵石")
    }
    await ForwardMsg(e, msg);
}

 /**
     * 常用查询合集
*/
export async function Go(e){
    let usr_qq = e.user_id;
    //有无存档
    let ifexistplay = await existplayer(usr_qq);
    if (!ifexistplay) {
        return ;
    }
       //获取游戏状态
    let game_action = await redis.get("xiuxian:player:" + usr_qq + ":game_action");
       //防止继续其他娱乐行为
       if(game_action==0){
           e.reply("修仙：游戏进行中...");
           return ;
     }
     //查询redis中的人物动作
    let action = await redis.get("xiuxian:player:" + usr_qq + ":action");
    action = JSON.parse(action);
    if (action != null) {
        //人物有动作查询动作结束时间
        let action_end_time = action.end_time;
        let now_time = new Date().getTime();
        if (now_time <= action_end_time) {
            let m = parseInt((action_end_time - now_time) / 1000 / 60);
            let s = parseInt(((action_end_time - now_time) - m * 60 * 1000) / 1000);
            e.reply("正在" + action.action + "中,剩余时间:" + m + "分" + s + "秒");
            return ;
        }
    }
    let player = await Read_player(usr_qq);
    if (player.当前血量 < 200) {
        e.reply("你都伤成这样了,就不要出去浪了");
        return ;
    }
    allaction=true;
    return ;
}